package nobu.nakata.nfcfare.datamapper;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.table.TrainStationHistory;

public class TrainStationHistoryDataMapper {
	private Cache cache;
	private PersistenceManager pm;
	
	
	public TrainStationHistoryDataMapper(Cache cache, PersistenceManager pm) {
		this.cache		= cache;
		this.pm			= pm;
	}
	
	
	public Collection<TrainStationHistory> findByTrainCode(Long trainCode) {
		String cacheKey = makeCacheKey(trainCode);
		Collection<TrainStationHistory> stored = (Collection<TrainStationHistory>) cache.get(cacheKey);
		if (stored != null)
			return stored;
		stored = loadFindByTrainCode(trainCode);
		return stored;
	}
	private Collection<TrainStationHistory> loadFindByTrainCode(Long trainCode) {
		Query qTrainStationHistory = pm.newQuery(TrainStationHistory.class);
		qTrainStationHistory.setFilter("trainCode == pTrainCode");
		qTrainStationHistory.declareParameters("Long pTrainCode");
		try {
			return pm.detachCopyAll((Collection<TrainStationHistory>) qTrainStationHistory.execute(trainCode));
		} finally {
			qTrainStationHistory.closeAll();
		}
	}
	
	public TrainStationHistory set(TrainStationHistory entity) {
		cache.remove(makeCacheKey(entity.getTrainCode()));
		return pm.detachCopy(pm.makePersistent(entity));
	}
	
	
	public static String makeCacheKey(Long trainCode) {
		return TrainStationHistory.KIND + ":" + trainCode;
	}
}
